package com.mti.app.model.business
{
	import com.google.zxing.BarcodeFormat;
	import com.google.zxing.MultiFormatWriter;
	import com.google.zxing.common.BitMatrix;
	
	import flash.display.BitmapData;
	import flash.net.FileReference;
	import flash.utils.ByteArray;
	
	import mx.graphics.codec.JPEGEncoder;
	
	import spark.primitives.BitmapImage;

	public class QRBuilder
	{
		
		static public function saveQR(image:BitmapImage):void
		{
			var jpg:JPEGEncoder = new JPEGEncoder();
			var ba:ByteArray = jpg.encode(image.bitmapData);
			var file:FileReference = new FileReference();
			file.save(ba, 'qrcode.jpg');
		}
					
		static public function createQr(content:String, size:int):BitmapData
		{
			var data:BitmapData = new BitmapData(size, size, false);
			var qrEncoder:MultiFormatWriter = new MultiFormatWriter();
			
			try
			{
				var codeMatrix:BitMatrix = BitMatrix(qrEncoder.encode(content, BarcodeFormat.QR_CODE, size, size));
			}
			catch (e:Error)
			{
				return null;
			}
			data.lock();
			for (var x:int = 0; x < size; x++)
			{
				for (var y:int = 0; y < size; y++)
				{
					data.setPixel(x, y, (codeMatrix._get(x, y) == true ? 0 : 0xffffff));        
				}
			}
			data.unlock();
			return data;
		}
	}
}